package mrusanov.ui.stats

import mrusanov.nation.{Nation, World}
import mrusanov.localization.Localization
import mrusanov.league.LeagueSystem
import mrusanov.tournament.{RoundRobinTournamentRound, KnockOutTournamentRound, TournamentRound, Tournament}

class TreeBuilder(world:World) {
  def buildTree = new TreeNode("root", buildMenuTree)

  private def buildMenuTree:List[TreeNode] = {
    val currentYear = world.currentYear
    val startingYear = world.seasons(0).year
    val yearsRange = (startingYear to currentYear).reverse
    yearsRange.map(buildMenuTreeForYear).toList
  }

  private def buildMenuTreeForYear(year:Int):TreeNode = {
    val nationsTrees = world.nations.map(n => buildMenuTreeForNation(year, n))
    val internationalTree = buildMenuTreeForInternational(year)
    val children = internationalTree :: nationsTrees
    new TreeNode(Localization("resultsPanel.season") + "" + year.toString, children)
  }

  private def buildMenuTreeForNation(year:Int, nation:Nation):TreeNode = {
    val season = world.season(year)
    val nationSeason = season.nationsSeasonsMap(nation)
    val firstNode = buildMenuTreeForLeagueSystem("resultsPanel.firstTeams", nationSeason.firstTeamsLeagueSystem)
    val secondNode = buildMenuTreeForLeagueSystem("resultsPanel.secondTeams", nationSeason.secondTeamsLeagueSystem)
    val juniorNode = buildMenuTreeForLeagueSystem("resultsPanel.juniorTeams", nationSeason.juniorTeamsLeagueSystem)
    val list = List(firstNode, secondNode, juniorNode)
    new TreeNode(nation.name, list)
  }

  private def buildMenuTreeForLeagueSystem(messageKey:String, system:LeagueSystem):TreeNode = {
    val children = system.leagues.map(buildMenuTreeForTournament).toList
    new TreeNode(Localization(messageKey),  children)
  }

  private def buildMenuTreeForInternational(year:Int):TreeNode = {
    val season = world.season(year)
    val tournaments = (season.goldenLeague ++ season.silverLeague).toList
    val children = tournaments.map(buildMenuTreeForTournament)
    new TreeNode(Localization("resultsPanel.international"), children)
  }

  private def buildMenuTreeForTournament(tournament:Tournament):TreeNode = {
    val children = tournament.rounds.zipWithIndex.map(kv => buildMenuTreeForTournamentRound(kv._2.toString, kv._1))
    new TreeNode(tournament.name, children.toList)
  }

  private def buildMenuTreeForTournamentRound(label:String, round:TournamentRound):TreeNode = {
    round match {
      case knockOut:KnockOutTournamentRound => new TreeLeaf(label, new KnockoutTournamentRoundPanel(knockOut))
      case roundRobin:RoundRobinTournamentRound => new TreeLeaf(label, new RoundRobinTournamentRoundPanel(roundRobin))
      case _ => throw new IllegalArgumentException("Unknown round type " + round.getClass.toString)
    }
  }
}

